<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>基本图形</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        canvas {
            border: 1px solid #eee;
        }

        #curChess {
            position: absolute;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            border: 1px dashed green;
            display: none;
            /* 指示该元素不是鼠标事件的目标; none表示鼠标事件“穿透”该元素并且指定该元素“下面”的任何东西 */
            pointer-events: none;
            box-sizing: border-box;
        }
    </style>
</head>

<canvas id="canvas" width="800" height="800"></canvas>
<div id="curChess"></div>
<script type="text/javascript">

    let bChessList = []  // 黑子棋子
    let wChessList = []  // 白子棋子
    let radius = 25

    let canvas = document.getElementById("canvas");
    let context = canvas.getContext("2d")

    let curChess = document.getElementById("curChess");


    // 3.画棋盘
    // 3.1 棋盘是由多条横线和纵线组合成的
    for (let i = 0; i <= 14; i++) {
        context.beginPath()
        context.moveTo(50 * i + 50, 50)
        context.lineTo(50 * i + 50, 750)
        context.stroke()

        context.moveTo(50, 50 * i + 50)
        context.lineTo(750, 50 * i + 50)
        context.stroke()
    }

    canvas.addEventListener('mousemove', function (e) {
        let {offsetX, offsetY} = e
        curChess.style.top = offsetY - radius + 'px'
        curChess.style.left = offsetX - radius + 'px'
    })
    canvas.addEventListener('mouseenter', function (e) {
        curChess.style.display = 'block'
    })
    canvas.addEventListener('mouseout', function (e) {
        curChess.style.display = 'none'
    })

    // 下棋
    canvas.addEventListener('click', function (e) {
        let {offsetX, offsetY} = e
        console.log("下的位置为--->", offsetX, offsetY)

        createChess(offsetX, offsetY)
        // (50,50) (700,50)
        // (50,750) (700,700)
    })

    // 426 306
    // 取商,就是当前点击的 横线或纵线的索引
    // Math.trunc(426/50)  Math.trunc(306/50)


    /** 创建棋子 **/
    function createChess(xPos, yPos) {
        let [x, y] = formatPos(xPos, yPos)
        context.beginPath()
        context.arc(x, y, radius, 0, 2 * Math.PI)

        let g = context.createLinearGradient(x - radius, y - radius, x + radius, y + radius)
        g.addColorStop(0, '#fff')
        g.addColorStop(1, '#000')
        context.fillStyle = g
        context.fill()
    }

    /** 格式化下棋位置 **/
    function formatPos(x, y) {
        let posX = Math.trunc(x / 50) * 50
        let posY = Math.trunc(y / 50) * 50
        return [posX, posY]
    }


</script>
</body>

</html>